<%-- 
    Document   : manage_roles
    Created on : 27 лют 2012, 21:49:03
    Author     : vlavrynovych
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    // TODO: change this by AppContentHelper
    String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "" + request.getContextPath();
%>
<style>
    .selected{
        background-color: #eed3d7 !important;
    }
</style>
<script type="text/javascript" src="<%=url%>/js/jquery.json-2.3.min.js"></script>
<script type="text/javascript">
    var $dialogRoles;
    var $roles;
    var $roleName;
    var $roleListTable;
    var $addEditRoleDialog;
    
    // request config
    var roleReq = {
        name: "",
        startIndex: 0,
        size: defaultListSize
    };
    
    //pager buttons
    var $rolePrev;
    var $roleNext;
    
    var $saveChanges;
    
    $.fn.hasAttr = function(name) {  
        return this.attr(name) !== undefined;
    };

    $(document).ready(function() {
        // pager
        $rolePrev = $('#rolePagerPrevButton');
        $roleNext = $('#rolePagerNextButton');
        
        $dialogRoles = $("#dialogRoles input");
        $roles = $("#createUserForm input:checked");
        $roleName = $("#roleName")
        $roleListTable = $("#roleListTable");
        $addEditRoleDialog = $("#addEditRoleDialog");
        
        roleRequest();
        
        $saveChanges = $('#saveChangesButton');
        updateSaveChangesButtonStatus();
    });
    
    function roleRequest(){
        $.ajax({
            url: "searchRoles.html",
            data: {
                name: roleReq.name,
                startIndex: roleReq.startIndex,
                size: roleReq.size
            },
            success: function(list, status) {
                if(status=="success"){
                    var globalRolePermissionsList;
                    $.getJSON("get_global_role_permissions.html", 
                        {}, 
                        function(globalRolePermissions) {
                            globalRolePermissionsList = globalRolePermissions;
                            $roleListTable.find("tr[id]").remove();
                            $rolePrev.attr("disabled",roleReq.startIndex==0);
                            $roleNext.attr("disabled",list.length!=roleReq.size+1);

                            if(list.length>0){
                                $.each(list, function(index, role){
                                    if(index<roleReq.size){
                                        // get sublist with permissions only for current role
                                        var rolePermissionsList = new Array();
                                        $.each(globalRolePermissionsList, function(index, permission) {
                                            if(permission.role.name == role.name) {
                                                rolePermissionsList.push(permission);
                                            }
                                        });
                                        addUpdateRoleRow(role, roleReq.startIndex+index+1, rolePermissionsList);
                                    }
                                });
                            } else {
                                if(roleReq.startIndex!=0 && roleReq.startIndex>=roleReq.size){
                                    roleReq.startIndex-=roleReq.size;
                                    roleRequest();
                                } else {
                                    noRecordsFound($roleListTable, 7);
                                }
                            }
                        }
                    );
                }
            }
        });
        
        refreshRoleCount();
    }
    
    function roleSearch(){
        roleReq.name = $('#search_role_name').val();
        roleReq.startIndex = 0;
        roleRequest();
    }
    
    // shows previous role list page
    function rolePagerNext(){
        if($roleNext.attr("disabled")) return;
        
        roleReq.startIndex = roleReq.startIndex+roleReq.size;
        roleRequest();
    }
    
    // shows next role list page
    function rolePagerPrev(){
        if($rolePrev.attr("disabled")) return;
        
        roleReq.startIndex = roleReq.startIndex-roleReq.size;
        roleRequest();
    }

    function addRole() {
        if($.trim($roleName.val()) != "") {
            $.ajax({
                url: "add_role.html",
                data: {name: $.trim($roleName.val())},
                success: function(resultMsg) {
                    if(resultMsg == "ok") {
                        roleRequest();
                        $roleName.val("");
                        Notifier.success("Role was successfully added.");
                    } else {
                        Notifier.error("Role was not added.");
                    }
                }
            });
        }
    }

    function updateRoleList(roleName) {
        $.getJSON(
        "get_role_by_name.html",
        {name: roleName},
        function(role) {
            addUpdateRoleRow(role);
        });
    }
    
    function getRoleRow(roleId){
        return $roleListTable.find($('#'+roleId));
    }
    
    function addUpdateRoleRow(role, number, rolePermissionsList){
        if (!role) return;
        var $row = getRoleRow(role.id);
        if ($row[0]==undefined){
            $row = addEmptyRoleRow(role.id, number)
        }

        // updates all values
        $row.find("td:nth-child(3)").html(role.name);
        
        for(i = 4; i<=7; i++){
            
            var checkBox = $("<input>");
            checkBox.attr("type","checkbox");
            
            $.each(rolePermissionsList, function(index, permission) {
                switch(i){
                    case 4:
                        if(permission.accessType.operationName == "Read block") {
                            checkBox.attr("checked","checked");
                        }
                        break;
                    case 5:
                        if(permission.accessType.operationName == "Delete block") {
                            checkBox.attr("checked","checked");
                        }
                        break;
                    case 6:
                        if(permission.accessType.operationName == "Update block") {
                            checkBox.attr("checked","checked");
                        }
                        break;
                    case 7:
                        if(permission.accessType.operationName == "Create block") {
                            checkBox.attr("checked","checked");
                        }
                        break;
                }
            });
            if(role.id == 1) {
                checkBox.attr("disabled", "true");
            }
            checkBox.attr('storedValue',checkBox.hasAttr('checked'));
            checkBox.attr('onclick','checkRolePermission(this)');
            
            $row.find("td:nth-child("+i+")").html(checkBox);
        }
    }
    
    function isPrmissionChanged(checkBox){
        return checkBox.attr('storedValue')!=checkBox.hasAttr('checked').toString();
    }
    
    function checkRolePermission(element){
        var checkBox = $(element);
        var td = checkBox.parent('td');
        
        if(isPrmissionChanged(checkBox)){
            td.addClass('selected');
        } else {
            td.removeClass('selected');
        }
        updateSaveChangesButtonStatus();
    }
    
    // adds one empty row with role ID
    function addEmptyRoleRow(roleId, number){
        var row = $("<tr>").attr('id',roleId);
        
        var numberCell = $("<td>").html(number);
        row.append(numberCell);

        var actionsCell = $("<td>");
        if(roleId != 1) {
            var deleteButton = $('<a>');
            deleteButton.attr('class','icon-trash');
            deleteButton.attr('onclick','deleteRole('+roleId+')');
            deleteButton.attr('title', 'Delete').tooltip();
            actionsCell.append(deleteButton);
        } else {
            actionsCell.append($('<a>').attr('class','icon-ban-circle'));
        }
        row.append(actionsCell); //actions cell

        //adds other cells
        for(var i = 0; i < 5; i++) {
            row.append($("<td>"));
        }

        $roleListTable.append(row);
        return row;
    }

    function deleteRole(roleId) {
        $.ajax({
            url: "remove_role/" + roleId + ".html",
            success: function(resultMsg) {
                hideAllTooltips();
                if(resultMsg == "ok") {
                    Notifier.success("Role was successfully deleted!");
                    roleRequest();
                } else {
                    Notifier.error(resultMsg, 'Error!');
                }
            }
        });
    }
       
    function showAddEditRoleDialog(roleId) {
        $addEditRoleDialog.modal();

        //sets  title for modal dialog
        $addEditRoleDialog.find('#modalTitle').text((roleId ? "Edit" : "Add") + " Role");
    }
    
    function onOkRoleModal(){
        addRole();
        onCancelRoleModal();
    }
    
    function onCancelRoleModal(){
        $addEditRoleDialog.modal("hide");
    }
    
    function updateAllStoredValues(){
        $changedCells = $roleListTable.find("td[class='selected']")
        $changedCells.each(function() {
            var checkbox = $(this).find("input");
            checkbox.attr('storedValue', checkbox.hasAttr('checked'));
        });
        $changedCells.removeClass('selected');
        updateSaveChangesButtonStatus();
    }
    
    function updateSaveChangesButtonStatus(){
        $saveChanges.attr("disabled",getChangedRolesRowsList().length==0);
    }
    
    function getChangedRolesRowsList(){
        return $roleListTable.find("tr[id]:has(td[class='selected'])");
    }
    
    function saveChanges() {
        if($saveChanges.attr("disabled")) return;
        var permissionsArray = new Array();
        
        getChangedRolesRowsList().each(function() {
            var object = new Object();
            var $row = $(this);
            object.roleId = $row.attr("id");
            object.read = $row.find("td:nth-child(4) input").attr("checked") ? true : false;
            object.remove = $row.find("td:nth-child(5) input").attr("checked") ? true : false;
            object.edit = $row.find("td:nth-child(6) input").attr("checked") ? true : false;
            object.create = $row.find("td:nth-child(7) input").attr("checked") ? true : false;
            permissionsArray.push(object);
        });
        
        if(permissionsArray.length==0) {
            Notifier.info('Changes was not found.');
            return;
        }

        $.ajax({
            url: "set_global_role_permissions.html",
            data: { 
                globalRights: JSON.stringify(permissionsArray)
            },
            success: function(resultMsg) {
                if(resultMsg == "ok") {
                    updateAllStoredValues();
                    Notifier.success("All global permissions were successfully saved");
                } else {
                    Notifier.error(resultMsg, "Error occurred!");
                }
            },
            type: "POST"
        });
    }
</script>

<div style="width: 94%; margin-left: 3%; margin-right: 3%" class="form-horizontal">
    <fieldset>
        <div class="well form-inline">
            <span>
                <a class="btn btn-primary" onclick="showAddEditRoleDialog()"><i class="icon-plus icon-white"></i> Add Role</a>
                <a class="btn" id="rolePagerPrevButton" onclick="rolePagerPrev()">Previous</a>
                <a class="btn" id="rolePagerNextButton" onclick="rolePagerNext()">Next</a>
                <a class="btn btn-success" id="saveChangesButton" onclick="saveChanges()"><i class="icon-ok icon-white"></i> Save Changes</a>
            </span>
            <span class="pull-right">
                <span class="input-prepend" style="width: 280px">
                    <span class="add-on">ROLE_</span>
                    <input id="search_role_name" type="text" class="input-large" placeholder="NAME">
                </span>
                <a class="btn" onclick="roleSearch()"><i class="icon-search"></i> Search</a>
                <a class="btn" onclick="roleRequest()"><i class="icon-refresh"></i> Refresh</a>
            </span>
        </div>

        <!-- Role list -->
        <table class="table table-striped table-condensed table-bordered" id="roleListTable">
            <thead>
                <tr style="background-color: #666666; color: white">
                    <th style="width: 20px">#</th>
                    <th style="width: 15px"><i class="icon-cog icon-white"/></th>
                    <th>Role Name</th>
                    <th style="width: 150px">Read</th>
                    <th style="width: 150px">Delete</th>
                    <th style="width: 150px">Edit</th>
                    <th style="width: 150px">Create</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </fieldset>
</div>

<div id="addEditRoleDialog" class="modal hide fade" style="display: table">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3 id="modalTitle"></h3>
    </div>
    
    <div class="modal-body form-horizontal">
        <div class="control-group">
            <label for="roleName" class="control-label">Role name</label>
            <div class="controls">
                <input type="text" id="roleName">
                <p class="help-block">Specify minimum 4 symbols</p>
            </div>
        </div>
    </div>
    
    <div class="modal-footer">
        <input type="button" class="btn" onclick="onCancelRoleModal()" value="Cancel"/>
        <input type="button" class="btn btn-primary" onclick="onOkRoleModal()" value="Ok"/>
    </div>
</div>